package com.rock.code.common.comm;

import org.springframework.beans.factory.FactoryBean;

import java.util.Properties;

/**
 * The type Encrypted data source factory.
 *
 * @author kongqiang
 * @date 2018 /02/07
 */
public class EncryptedDataSourceFactory implements FactoryBean {

    /**
     * The Properties.
     */
    private Properties properties;

    /**
     * Gets object.
     *
     * @return the object
     * @throws Exception the exception
     * @author kongqiang
     * @date 2018 /02/07
     */
    public Object getObject() throws Exception {
        return getProperties();
    }

    /**
     * Gets object type.
     *
     * @return the object type
     * @author kongqiang
     * @date 2018 /02/07
     */
    public Class getObjectType() {
        return java.util.Properties.class;
    }

    /**
     * Is singleton boolean.
     *
     * @return the boolean
     * @author kongqiang
     * @date 2018 /02/07
     */
    public boolean isSingleton() {
        return true;
    }

    /**
     * Gets properties.
     *
     * @return the properties
     * @author kongqiang
     * @date 2018 /02/07
     */
    public Properties getProperties() {
        return properties;
    }

    /**
     * Sets properties.
     *
     * @param inProperties the in properties
     * @author kongqiang
     * @date 2018 /02/07
     */
    public void setProperties(Properties inProperties) {
        this.properties = inProperties;
        String originalUsername = properties.getProperty("user");
        String originalPassword = properties.getProperty("password");
        if (originalUsername != null) {
            String newUsername = decryptDESUsername(originalUsername);
            properties.put("user", newUsername);
        }
        if (originalPassword != null) {
            String newPassword = decryptDESPassword(originalPassword);
            properties.put("password", newPassword);
        }
    }

    /**
     * Decrypt des username string.
     *
     * @param originalUsername the original username
     * @return the string
     * @author kongqiang
     * @date 2018 /02/07
     */
    private String decryptDESUsername(String originalUsername) {
        return DES3.decode(originalUsername);
    }

    /**
     * Decrypt des password string.
     *
     * @param originalPassword the original password
     * @return the string
     * @author kongqiang
     * @date 2018 /02/07
     */
    private String decryptDESPassword(String originalPassword) {
        return DES3.decode(originalPassword);
    }

}
